<template>
  <!-- <n-infinite-scroll :distance="0" @load="handleLoad"> -->
  <div class="flex overflow-auto pb-[24px]" ref="scrollContainer">
    <div class="m-auto w">
      <n-spin :show="SNLoading" v-if="mode != 'image'">
        <div
          class="bg-[#fff] px-[20px] pt-[10px] min-h-[100px] mt-[24px]"
          v-if="SNLoading || !!keywordSNQueryData?.length"
        >
          <div
            v-for="item in keywordSNQueryData"
            :key="item.id"
            class="search-items flex items-center py-[10px]"
          >
            <div class="w-[168px] text-[#767676] text-[14px] mr-[20px] leading-[20px]">
              {{ item.translateName }}
              <template v-if="isDev">
                {{ item.name }}
                {{ item.id }}
              </template>
            </div>
            <div class="flex-1 w-0 flex flex-wrap gap-[10px]">
              <div
                class="text-[#1A1A1A] font-[400]"
                v-for="t in item.children"
                :key="t.id"
                @click="onClickSN(item.id, t)"
              >
                <n-tag
                  :bordered="false"
                  round
                  class="cursor-pointer text-[16px]"
                  :color="
                    selectSNList.includes(t.id)
                      ? { color: 'var(--main-color)', textColor: '#fff' }
                      : { color: 'transparent', textColor: '#1A1A1A' }
                  "
                >
                  {{ t.translateName }}
                  <template v-if="isDev">
                    {{ t.name }}
                    {{ t.id }}
                  </template>
                </n-tag>
              </div>
            </div>
          </div>
        </div>
      </n-spin>
      <div class="bg-[#fff] px-[20px] mt-[24px]">
        <n-checkbox-group :value="filterData" @update:value="onChangeFilter">
          <div class="search-items flex items-center py-[10px] gap-[40px]">
            <div class="w-[380px] flex items-center gap-2">
              <div>{{ $t("common.店铺评级") }}</div>
              <div class="flex-1">
                <n-select
                  :placeholder="$t('SNQuery.无限制')"
                  clearable
                  @update:value="onSelectEpScore"
                  :options="[
                    { label: '5 estrella', value: 'totalEpScoreLv1' },
                    { label: '4.5 estrella - 5.0 estrella', value: 'totalEpScoreLv2' },
                    { label: '4 estrella - 4.5 estrella', value: 'totalEpScoreLv3' },
                    { label: 'Menos de 4 estrellas', value: 'totalEpScoreLv4' },
                  ]"
                />
              </div>
            </div>

            <div>
              <n-checkbox value="certifiedFactory">
                {{ $t("SNQuery.认证工厂") }}
              </n-checkbox>
            </div>
            <div>
              <n-checkbox value="shipInToday">{{ $t("SNQuery.当天发货") }}</n-checkbox>
            </div>
            <div>
              <n-checkbox value="shipIn24Hours">
                {{ $t("SNQuery.二十四小时发货") }}
              </n-checkbox>
            </div>
            <div>
              <n-checkbox value="shipIn48Hours">
                {{ $t("SNQuery.四十八小时发货") }}
              </n-checkbox>
            </div>
            <div>
              <n-checkbox value="noReason7DReturn">
                {{ $t("SNQuery.七天无理由") }}
              </n-checkbox>
            </div>
          </div>
          <div class="search-items flex items-center py-[10px] gap-[40px]">
            <div
              class="cursor-pointer"
              :class="!sortData ? 'text-[--main-color]' : ''"
              @click="onClickSort('')"
            >
              {{ $t("SNQuery.综合排序") }}
            </div>
            <div
              class="flex items-center cursor-pointer"
              @click="onClickSort('monthSold')"
            >
              <div :class="sortData?.monthSold ? 'text-[--main-color]' : ''">
                {{ $t("SNQuery.月销排序") }}
              </div>
              <div class="flex sort-wrapper">
                <n-icon
                  :class="sortData?.monthSold == 'asc' ? '!text-[--main-color]' : ''"
                >
                  <CaretUp></CaretUp>
                </n-icon>
                <n-icon
                  :class="sortData?.monthSold == 'desc' ? '!text-[--main-color]' : ''"
                >
                  <CaretDown></CaretDown>
                </n-icon>
              </div>
            </div>

            <div
              class="flex items-center cursor-pointer"
              @click="onClickSort('rePurchaseRate')"
            >
              <div :class="sortData?.rePurchaseRate ? 'text-[--main-color]' : ''">
                {{ $t("SNQuery.重复购买率排序") }}
              </div>
              <div class="flex sort-wrapper">
                <n-icon
                  :class="sortData?.rePurchaseRate == 'asc' ? '!text-[--main-color]' : ''"
                >
                  <CaretUp></CaretUp>
                </n-icon>
                <n-icon
                  :class="
                    sortData?.rePurchaseRate == 'desc' ? '!text-[--main-color]' : ''
                  "
                >
                  <CaretDown></CaretDown>
                </n-icon>
              </div>
            </div>

            <div class="flex items-center cursor-pointer" @click="onClickSort('price')">
              <div :class="sortData?.price ? 'text-[--main-color]' : ''">
                {{ $t("common.单价") }}
              </div>
              <div class="flex sort-wrapper">
                <n-icon :class="sortData?.price == 'asc' ? '!text-[--main-color]' : ''">
                  <CaretUp></CaretUp>
                </n-icon>
                <n-icon :class="sortData?.price == 'desc' ? '!text-[--main-color]' : ''">
                  <CaretDown></CaretDown>
                </n-icon>
              </div>
            </div>

            <div class="flex items-center gap-2">
              <n-input-number
                class="w-[150px]"
                placeholder="Precio más bajo"
                :show-button="false"
                :min="0"
                v-model:value="request.priceStart"
              >
                <template #prefix> ￥ </template>
              </n-input-number>
              <span>-</span>
              <n-input-number
                class="w-[150px]"
                placeholder="Precio más alto"
                :show-button="false"
                :min="0"
                v-model:value="request.priceEnd"
              >
                <template #prefix> ￥ </template>
              </n-input-number>
              <n-button class="ml-[10px]" type="primary" @click="onConfirmPrice">
                {{ $t("button.确定") }}
              </n-button>
            </div>
          </div>
        </n-checkbox-group>
      </div>
      <div class="w m-auto mt-[24px]">
        <div class="w m-auto mt-[24px] grid grid-cols-5 gap-4" v-if="!noResult">
          <div class="flex-1" v-for="item in goodsList" :key="item.offerId">
            <goodsCard :goods="item"></goodsCard>
          </div>
        </div>

        <template v-else>
          <div
            class="w-[700px] mx-auto text-center my-[110px] text-[22px] font-[400] text-[#2f2f2f] leading-[36px]"
          >
            {{ $t("tips.未搜索到商品") }}
          </div>
        </template>
      </div>

      <div class="w text-center p-[100px]" v-show="loading && !showPageBar">
        <n-spin size="medium" />
      </div>
      <!-- 
        <n-pagination
          v-model:page="result.currentPage"
          :page-count="result.totalPage"
          @on-update:page="onChangePage"
        /> -->

      <!-- <div
          ref="loadMoreTrigger"
          class="load-more-trigger"
          v-show="!loading && canLoadMore"
        >
          上滑加载
        </div> -->

      <div class="flex mt-[24px]" v-if="showPageBar">
        <!-- <n-pagination
            class="m-auto"
            v-model:page="result.currentPage"
            :page-count="result.totalPage"
            @update:page="onClickPage"
          /> -->

        <n-button
          :loading="loading"
          type="primary"
          class="m-auto"
          @click="onClickLoadMore"
          ghost
        >
          {{ $t("button.加载更多") }}
        </n-button>
      </div>
    </div>
  </div>
  <!-- </n-infinite-scroll> -->
</template>

<script setup>
import { ref } from "vue";
import { keywordSNQuery, commoditySearch, imageQuery } from "@/api/product";
import { useRoute } from "vue-router";
import goodsCard from "@/components/goodsCard.vue";
import { CaretUp, CaretDown } from "@vicons/carbon";
import bus from "@/utils/mitt";
import { hidenSn, defaultSn } from "@/utils/keywordSNQuery";
const route = useRoute();
const isDev = import.meta.env.MODE == "development";
const keywords = ref(route.params.keyword);
const searchType = ref(route.params.type);
const loading = ref(false);
const mode = ref("");
const keywordSNQueryData = ref([]);
const selectSNList = ref([]);
const goodsList = ref([]);
const result = ref({
  currentPage: 0,
  totalPage: 1,
});
const request = ref({
  pageSize: 20,
  page: 1,
  priceStart: undefined,
  priceEnd: undefined,
  imageId: undefined,
});

const emit = defineEmits(["loadCallback"]);
const sortData = ref(null);
const noResult = ref(false);
const filterData = ref([]);
const scrollContainer = ref(null);
const allowLoad = ref(false);
const canLoadMore = computed(
  () => !loading.value && result.value.currentPage <= result.value.totalPage
);
const showPageBar = ref(false);
// const hidenSn = ["182282223", "7869", "100000691"]; //["是否跨境出口专供货源"]
// const defaultSn = ["182282223:21958"];
const maxPage = 3;
const SNLoading = ref(false);
const keywordSNQueryHandle = async () => {
  if (mode.value == "image") return;
  SNLoading.value = true;
  try {
    const { data } = await keywordSNQuery(keywords.value);
    // const defaultSNData = data.data?.filter((x) => hidenSn.includes(x.id));
    keywordSNQueryData.value = data.data?.filter((x) => !hidenSn.includes(x.id));
    // keywordSNQueryData.value = data.data;
  } catch (error) {
  } finally {
    SNLoading.value = false;
  }
};

// watch(
//   () => route.params.keyword,
//   (newVal) => {
//     keywords.value = newVal;
//     initSearch(true);
//   }
// );

const initSearch = async (resetSn) => {
  result.value = {
    currentPage: 0,
    totalPage: 1,
  };
  request.value.page = 1;
  goodsList.value = [];
  showPageBar.value = false;
  await commoditySearchHandle();
  if (resetSn) {
    selectSNList.value = [];
    await keywordSNQueryHandle();
  }
};

onMounted(() => {
  // initSearch(true);

  bus.on("searchByKeyword", (data) => {
    keywords.value = data;
    initSearch(true);
  });
});

onUnmounted(() => {
  bus.off("searchByKeyword");
});

const commoditySearchHandle = async () => {
  if (!allowLoad.value) return;
  if (!canLoadMore.value) return;
  loading.value = true;
  try {
    const sn = defaultSn.concat(selectSNList.value);
    let _requestData = {
      keywords: keywords.value,
      ...request.value,
      filter: filterData.value?.join(",") || "",
      sort: sortData.value ? JSON.stringify(sortData.value) : "",
      country: "es",
    };
    const { data } =
      mode.value == "image"
        ? await imageQuery({
            ..._requestData,
            beginPage: request.value.page,
          })
        : await commoditySearch({
            ..._requestData,
            snId: sn.join(","),
          });

    const { currentPage, pageSize, totalPage, totalRecords, picRegionInfo } = data.data;
    result.value = { currentPage, pageSize, totalPage, totalRecords, picRegionInfo };

    emit("loadCallback", data.data, request.value.imageId);
    request.value.page = currentPage;
    if (!data.data.data || data.data.data.length == 0) {
      //本次查询没有结果
      noResult.value = !goodsList.value || goodsList.value.length === 0;
    } else {
      // if (showPageBar.value) {
      //   goodsList.value = data.data.data;
      // } else {
      goodsList.value.push(...data.data.data);
      // }
      noResult.value = false;
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const onClickSN = (pid, t) => {
  if (selectSNList.value.includes(t.id)) {
    selectSNList.value = selectSNList.value.filter((x) => x != t.id);
  } else {
    let l = selectSNList.value.filter((x) => x.startsWith(pid + ":"));
    if (l.length > 0) {
      //当前父节点下已有子节点存在 则移出
      selectSNList.value = selectSNList.value.filter((x) => !x.startsWith(pid + ":"));
    }
    selectSNList.value.push(t.id);
  }
  result.value = {
    currentPage: 0,
    totalPage: 1,
  };
  initSearch();
};

onMounted(() => {
  window.addEventListener("scroll", handleScroll);
});

onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});

// 滚动事件处理器
const handleScroll = () => {
  if (!allowLoad.value) return;
  //   if (!loadMoreTrigger.value || !scrollContainer.value) return;
  const scrollTop = window.scrollY;
  const documentHeight = Math.max(
    document.body.scrollHeight,
    document.documentElement.scrollHeight
  );
  const windowHeight = window.innerHeight;

  // 判断是否触底
  if (scrollTop + windowHeight >= documentHeight - 500 && canLoadMore.value) {
    if (request.value.page >= maxPage || showPageBar.value) {
      showPageBar.value = true;
      return;
    }
    request.value.page += 1;
    commoditySearchHandle();
  }
};

const onChangeFilter = (value) => {
  filterData.value = value;
  initSearch();
};

const onSelectEpScore = (value) => {
  // if (!value || filterData.value.find((x) => x.startsWith("totalEpScoreLv"))) {
  //   filterData.value =

  // }
  filterData.value =
    filterData.value.filter((x) => !x.startsWith("totalEpScoreLv")) || [];
  if (value) filterData.value.push(value);
  initSearch();
};

const onConfirmPrice = () => {
  initSearch();
  // commoditySearchHandle();
};

const onClickSort = (key) => {
  if (key) {
    if (!sortData.value || !sortData.value[key]) sortData.value = {};
    sortData.value[key] = sortData.value[key] === "desc" ? "asc" : "desc";
  } else {
    sortData.value = null;
  }

  initSearch();
  // commoditySearchHandle();
};

const onClickPage = async (page) => {
  request.value.page = page;
  await commoditySearchHandle();
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};

const onClickLoadMore = async () => {
  request.value.page += 1;
  commoditySearchHandle();
};

const pageLoaded = (data) => {
  allowLoad.value = true;
  mode.value = data?.type;
  if (mode.value == "image") {
    request.value.imageId = data.imageId;
    request.value.region = data.region;
  }
  initSearch(true);
};
defineExpose({ pageLoaded });
</script>

<style lang="scss" scoped>
.search-items {
  border-bottom: 1px solid #d8d8d8;
  &:last-child {
    border-bottom: none;
  }
}

.sort-wrapper {
  position: relative;
  width: 16px;
  i {
    position: absolute;
    right: 0;
    color: #cccccc;
    &:first-child {
      bottom: -3px;
    }
    &:last-child {
      top: -3px;
    }
  }
}
</style>
